﻿// Markup types
var MARKUP_BOLD = "b";
var MARKUP_CODE = "code";
var MARKUP_FILE = "file";
var MARKUP_ITALIC = "i";
var MARKUP_LINK = "link";
var MARKUP_LIST = "list";
var MARKUP_UNDERLINE = "u";

// Add markup to textarea
$.fn.addMarkup = function (type) {

    // Define return function
    return this.each(function () {

        // Get selection range
        var selectLength = this.value.length;
        var selectBegin = this.selectionStart;
        var selectEnd = this.selectionEnd;

        // Get selected text
        var selectedText = this.value.substring(selectBegin, selectEnd);

        // Set replacement text
        var replaceText = (type == MARKUP_FILE || type == MARKUP_LINK) ?
            "[" + type + " url=\"\"]" + selectedText + "[/" + type + "]" :
            "[" + type + "]" + selectedText + "[/" + type + "]";

        // Update value
        this.value = this.value.substring(0, selectBegin) + replaceText +
            this.value.substring(selectEnd, selectLength);

        // Set new caret position
        var typeLength = type.length;
        var caret = selectBegin + typeLength + 2;
        if (type == MARKUP_FILE || type == MARKUP_LINK) caret = selectBegin + typeLength + 7;

        // Check for setSelectionRange property
        if (this.setSelectionRange) {

            // Focus and set position
            this.focus();
            this.setSelectionRange(caret, caret);

        } else if (this.createTextRange) {

            // Focus and set position
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd("character", caret);
            range.moveStart("character", caret);
            range.select();

        };

    });

};